package cocurrent;

import org.junit.Test;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Exchanger;

/**
 * 交换机    线程之间交换信息   没有得到对方的回应时，双方进入阻塞  都接到信息后 同时解除阻塞
 */
public class ExchangeTest {
    private CountDownLatch countDownLatch = new CountDownLatch(2);

    @Test
    public void test() throws InterruptedException {
        Exchanger<String> exchanger = new Exchanger<>();
        Thread thread = new Thread(() -> {
            String content = null;
            try {
                content = exchanger.exchange("hahah");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("thread1 out~~" + content);
            countDownLatch.countDown();

        });
        thread.start();

        Thread thread2 = new Thread(() -> {
            String content = null;
            try {
                content = exchanger.exchange("hahah2");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("thread2 out~~" + content);
            countDownLatch.countDown();
        });
        thread2.start();
        countDownLatch.await();
    }
}
